//
//  SendIdcodeViewController.m
//  myhuibao
//
//  Created by lijun on 13-4-16.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "SendIdcodeViewController.h"
#import <UIKit/UIKit.h>
#import<mach/mach_time.h>
#import "RegisterViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import "Config.h"
#import "MemberViewController.h"
#import<QuartzCore/QuartzCore.h>
#import "RegAgreementViewController.h"
@interface SendIdcodeViewController ()

@end

@implementation SendIdcodeViewController
@synthesize code;
@synthesize password;
@synthesize confirmpwd;
@synthesize phone;
@synthesize btnSave;
//static int type=0;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _userView.layer.cornerRadius=3;
    _userView.layer.borderWidth=1;
    _userView.layer.borderColor= TEXTFIELD_COLOR.CGColor;
    _passwordView.layer.cornerRadius=3;
    _passwordView.layer.borderWidth=1;
    _passwordView.layer.borderColor= TEXTFIELD_COLOR.CGColor;
    _password1View.layer.cornerRadius=3;
    _password1View.layer.borderWidth=1;
    _password1View.layer.borderColor= TEXTFIELD_COLOR.CGColor;
    _password2View.layer.cornerRadius=3;
    _password2View.layer.borderWidth=1;
    _password2View.layer.borderColor= TEXTFIELD_COLOR.CGColor;
	// Do any additional setup after loading the view.
    phone.delegate = self, code.delegate = self,password.delegate = self;
    tickCount=0;
}

- (void)viewDidUnload
{
    [self setPassword:nil];
    [self setCode:nil];
    [self setConfirmpwd:nil];
    [self setUserView:nil];
    [self setPasswordView:nil];
    [self setPassword1View:nil];
    [self setPassword2View:nil];
    [self setPhone:nil];
    [super viewDidUnload];
   
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    if([[dic valueForKey:@"status"] isEqualToString:@"ERROR"]){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:
        [dic valueForKey:@"log"]
                                                    delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    NSDictionary *data = [dic valueForKey:@"data"];
   // NSLog(@"%@",data);
    if([data valueForKey:@"memberID"]!=0){
        NSString *md5 = [[Config Instance]md5HexDigest:password.text];
        [[Config Instance] setPassword:md5];
        [[Config Instance] setMemberId:[[data valueForKey:@"memberID"] intValue]];
        [[Config Instance]setPhone:phone.text];
        [[Config Instance] setIsLogin:YES];
        [[Config Instance]setNickName:@""];
        MemberViewController *view=[[MemberViewController alloc]initWithNibName:@"MemberViewController" bundle:nil];
        [self.navigationController pushViewController:view animated:YES];
    }
    
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)againCode:(id)sender {
    if([phone.text isEqualToString:@"" ]||[phone.text  isEqual:nil]){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:@"您还没有输入手机号码哦!"delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if([Config isMobileNumber:phone.text]==NO ){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:@"请输入11位的手机号码"delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    int curtime=[self mxGetTickCount]/1000;
    if(curtime-tickCount<=60)
    {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:@"请不要在一分钟之内重复获取验证码"delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;

    }
    NSURL *url=[NSURL URLWithString:url_reg];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setPostValue:phone.text forKey:@"member.mobile"];
    [request setDidFinishSelector:@selector(finishIdentify:)];

    [request setDelegate:self];
    [request startAsynchronous];
    second=60;
    timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(TimerCode) userInfo:nil repeats:YES];
    
}

-(void)TimerCode
{
    if(second==0)
    {
        [_btnCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        [timer invalidate];
        timer=nil;
        return;
    }
    [_btnCode setTitle:[NSString stringWithFormat:@"%d秒后重新获取",second--] forState:UIControlStateNormal];
}

- (void)finishIdentify:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    //    if([[dic valueForKey:@"status"] isEqualToString:@"ERROR"]){
    //        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:
    //                            [dic valueForKey:@"log"]
    //                                                    delegate:nil
    //                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    //        [alert show];
    //        [alert release];
    //        phone.text=nil;
    //        return;
    //    }
    
    if ([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:
                            @"请查收验证码短信"
                                                    delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        tickCount= [self mxGetTickCount]/1000;
        return;
    }
    else{
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:
                            [dic valueForKey:@"log"]
                                                    delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }

}
- (IBAction)reg2Login:(id)sender {
    if([phone.text isEqualToString:@"" ]||[phone.text  isEqual:nil]){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:@"您还没有输入手机号码哦!"delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if([Config isMobileNumber:phone.text]==NO ){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:@"请输入11位的手机号码"delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if([code.text isEqual:nil]||[code.text isEqualToString:@""]){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:@"您还没有输入验证码哦!"delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if([password.text isEqual:nil]||password.text.length<6|| password.text.length>16){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:@"请输入6~16位密码!"delegate:nil
                                           cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if(![password.text isEqualToString:confirmpwd.text]){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:@"两次输入的密码不一致"delegate:nil
            cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    NSURL *url=[NSURL URLWithString:url_reg2login];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setPostValue:phone.text forKey:@"member.mobile"];
    [request setPostValue:password.text forKey:@"member.password"];
    [request setPostValue:[code.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] forKey:@"identifyingCode"];
    [request setPostValue:[NSString stringWithFormat:@"%d",[[Config Instance] getCityId]] forKey:@"cityID"];
    [request setDelegate:self];
    [request startAsynchronous];
}

- (IBAction)goBack:(id)sender {
    if(timer!=nil)
    {
        [timer invalidate];
        timer=nil;
    }
     [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)doEdit:(id)sender {
//    float height = 256.0;
//    CGRect frame = self.view.frame;
//    frame.origin.y=(frame.size.height-self.btnSave.frame.size.height-self.btnSave.frame.origin.y)-height;
//    [UIView beginAnimations:@"Curl"context:nil];//动画开始
//    [UIView setAnimationDuration:0.30];
//    [UIView setAnimationDelegate:self];
//    [self.view setFrame:frame];
//    [UIView commitAnimations];
}

- (IBAction)endEdit:(id)sender {
//    NSTimeInterval animationDuration = 0.30f;
//    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
//    [UIView setAnimationDuration:animationDuration];
//    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
//    self.view.frame = rect;
//    [UIView commitAnimations];
    [confirmpwd resignFirstResponder];
}

- (IBAction)showAgreement:(id)sender {
    RegAgreementViewController *view=[[RegAgreementViewController alloc]initWithNibName:@"RegAgreementViewController" bundle:nil];
    [self.navigationController pushViewController:view animated:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    //    if (theTextField == self.textField) {
    [theTextField resignFirstResponder];
    //    }
    return YES;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSSet *allTouches = [event allTouches];
    
    switch ([allTouches count]) {
        case 1: {
            // potential pan gesture
            [self.phone resignFirstResponder];
        } break;
    }
}
- (int)mxGetTickCount;
{
    int timeTick;
    mach_timebase_info_data_t info;
    uint64_t machineTime;
    mach_timebase_info(&info);
    machineTime =mach_absolute_time();
    timeTick = machineTime * info.numer / info.denom /1000000LL;
    
    return timeTick;
}
@end
